package com.yipei.business.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yipei.business.domain.MlImportantNews;
import com.yipei.business.mapper.MlImportantNewsMapper;
import com.yipei.business.service.IMlImportantNewsService;
import com.yipei.common.config.RuoYiConfig;
import com.yipei.common.core.domain.AjaxResult;
import com.yipei.common.utils.DateUtils;
import com.yipei.common.utils.StringUtils;
import com.yipei.common.utils.file.FileUploadUtils;
import com.yipei.common.utils.file.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * 新闻要闻Service业务层处理
 *
 * @author yipei
 * @date 2024-12-21
 */
@Service
public class MlImportantNewsServiceImpl implements IMlImportantNewsService {
    @Autowired
    private MlImportantNewsMapper mlImportantNewsMapper;
    @Value("${location.host}")
    private String host;
    /**
     * 查询新闻要闻
     *
     * @param id 新闻要闻主键
     * @return 新闻要闻
     */
    @Override
    public MlImportantNews selectMlImportantNewsById(Long id) {
        return mlImportantNewsMapper.selectMlImportantNewsById(id);
    }

    /**
     * 查询新闻要闻列表
     *
     * @param mlImportantNews 新闻要闻
     * @return 新闻要闻
     */
    @Override
    public List<MlImportantNews> selectMlImportantNewsList(MlImportantNews mlImportantNews) {
        return mlImportantNewsMapper.selectMlImportantNewsList(mlImportantNews);
    }

    /**
     * 新增新闻要闻
     *
     * @param mlImportantNews 新闻要闻
     * @return 结果
     */
    @Override
    public int insertMlImportantNews(MlImportantNews mlImportantNews) {
        mlImportantNews.setCreateTime(DateUtils.getNowDate());
        return mlImportantNewsMapper.insertMlImportantNews(mlImportantNews);
    }

    /**
     * 修改新闻要闻
     *
     * @param mlImportantNews 新闻要闻
     * @return 结果
     */
    @Override
    public int updateMlImportantNews(MlImportantNews mlImportantNews) {
        mlImportantNews.setUpdateTime(DateUtils.getNowDate());
        return mlImportantNewsMapper.updateMlImportantNews(mlImportantNews);
    }

    /**
     * 批量删除新闻要闻
     *
     * @param ids 需要删除的新闻要闻主键
     * @return 结果
     */
    @Override
    public int deleteMlImportantNewsByIds(Long[] ids) {
        return mlImportantNewsMapper.deleteMlImportantNewsByIds(ids);
    }

    /**
     * 删除新闻要闻信息
     *
     * @param id 新闻要闻主键
     * @return 结果
     */
    @Override
    public int deleteMlImportantNewsById(Long id) {
        return mlImportantNewsMapper.deleteMlImportantNewsById(id);
    }


    @Override
    public void addImporttantNews() throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet("https://np-listapi.eastmoney.com/comm/web/getNewsByColumns?client=web&biz=web_news_col&column=365&order=1&needInteractData=0&page_index=1&page_size=20&req_trace=1735612867752"); //示例URL，请替换为实际的股票代码
        request.setHeader("Content-Type", "text/javascript;charset=UTF-8");
        HttpResponse response = client.execute(request);
        List<MlImportantNews> list = new ArrayList<>();
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(result).getJSONObject("data");
            JSONArray list1 = jsonObject.getJSONArray("list");
            list = list1.toJavaList(MlImportantNews.class).subList(0, 20);
            for (MlImportantNews importantNews : list) {
                importantNews.setContent(importantNews.getSummary());
                importantNews.setFbSj(importantNews.getShowTime());
                importantNews.setXwLy(importantNews.getMediaName());
                String image = importantNews.getImage();
                if (StringUtils.isNotEmpty(image)) {
                    MultipartFile multipartFile = this.downloadFileAsMultipartFile(image, importantNews.getMediaName());
                    AjaxResult ajaxResult = this.uploadFile(multipartFile);
                    importantNews.setImg(String.valueOf(ajaxResult.get("fileName")));
                }
            }
        }
        for (MlImportantNews mlImportantNews : list) {
            this.insertMlImportantNews(mlImportantNews);
        }
    }

    @Override
    public MultipartFile downloadFileAsMultipartFile(String fileUrl, String fileName) throws Exception {
        URL url = new URL(fileUrl);
        URLConnection connection = url.openConnection();
        String contentType = connection.getContentType(); // 自动获取图片类型
        InputStream inputStream = connection.getInputStream();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n;
        while ((n = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, n);
        }
        inputStream.close();

        // 转为MultipartFile
        MultipartFile multipartFile = new MockMultipartFile(
                fileName, // 文件名
                fileName, // 原始文件名
                contentType, // 自动识别图片类型
                outputStream.toByteArray()
        );
        return multipartFile;
    }

    @Override
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        {
            try {
                // 上传文件路径
                String filePath = RuoYiConfig.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = host + fileName;
                AjaxResult ajax = AjaxResult.success();
                ajax.put("url", url);
                ajax.put("fileName", url);
                ajax.put("newFileName", FileUtils.getName(fileName));
                ajax.put("originalFilename", file.getOriginalFilename());
                return ajax;
            } catch (Exception e) {
                return AjaxResult.error(e.getMessage());
            }
        }
    }
}
